package com.applink.sell_proof.urlimageviewhelper;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.applink.sell_proof.R;
import com.applink.sell_proof.database.table.ImageDBHelper;
import com.applink.sell_proof.model.ClaimImage;
import com.applink.sell_proof.model.MyImage;
import com.applink.sell_proof.urlimageviewhelper.InputStreamWrapper.InputStreamProgressListener;
import com.applink.sell_proof.util.Utility;

public class UrlTouchClaimImageView extends RelativeLayout {

	protected ProgressBar mProgressBar;
	protected RotateImageView mImageView;
	protected Context mContext;

	public UrlTouchClaimImageView(Context context) {
		super(context);
		mContext = context;
		init();
	}

	public UrlTouchClaimImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}

	public RotateImageView getImageView() {
		return mImageView;
	}

	protected void init() {
		mImageView = new RotateImageView(mContext);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		mImageView.setLayoutParams(params);
		this.addView(mImageView);
		mImageView.setVisibility(GONE);

		mProgressBar = new ProgressBar(mContext, null,
				android.R.attr.progressBarStyleHorizontal);
		params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.CENTER_VERTICAL);
		params.setMargins(30, 0, 30, 0);
		mProgressBar.setLayoutParams(params);
		mProgressBar.setIndeterminate(false);
		mProgressBar.setMax(100);
		this.addView(mProgressBar);
	}

	public void setClaimImage(MyImage image) {
		new ImageLoadTask().execute(image);
	}

	private MyImage mClaimImage;

	// No caching load
	public class ImageLoadTask extends AsyncTask<Object, Integer, Bitmap> {

		private Bitmap getBitmap(String url) {
			Bitmap bm = null;
			try {

				URL aURL = new URL(url);

				Options o = Utility.getBitmapOption(mContext, aURL);

				URLConnection conn = aURL.openConnection();
				conn.connect();

				InputStream is = conn.getInputStream();
				int totalLen = conn.getContentLength();

				InputStreamWrapper bis = new InputStreamWrapper(is, 8192,
						totalLen);

				bis.setProgressListener(new InputStreamProgressListener() {
					@Override
					public void onProgress(float progressValue,
							long bytesLoaded, long bytesTotal) {
						publishProgress((int) (progressValue * 100));
					}
				});

				bm = BitmapFactory.decodeStream(bis, null, o);

				bis.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return bm;
		}

		private void hanldeBitmap(Bitmap bitmap) {

			if (bitmap == null) {
				mImageView.setScaleType(ScaleType.CENTER);
				bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.no_photo);
				mImageView.setImageBitmap(bitmap);
			} else {
				mImageView.setScaleType(ScaleType.MATRIX);
				mImageView.setImageBitmap(bitmap);
			}

			mImageView.setVisibility(INVISIBLE);
			mProgressBar.setVisibility(GONE);

			if (mClaimImage instanceof ClaimImage)
				new Handler().post(new Runnable() {

					@Override
					public void run() {
						mImageView.doRotate(((ClaimImage) mClaimImage)
								.getRotateDegree());
						mImageView.setVisibility(VISIBLE);
					}
				});
			else
				mImageView.setVisibility(VISIBLE);
		}

		@Override
		protected Bitmap doInBackground(Object... objs) {

			mClaimImage = (MyImage) objs[0];

			Uri u = mClaimImage.getImageLocation();

			if (u.getScheme().toLowerCase().equals("file")) {

				ImageDBHelper.insertPaths(mClaimImage.getImageLocation()
						.toString(), mClaimImage.getImageLocation().toString());

				return getBitmap(mClaimImage.getImageLocation().toString());
			} else {

				String localpath = ImageDBHelper.getCachePath(mClaimImage
						.getImageLocation().toString());

				if (!localpath.equals(""))
					return getBitmap(localpath);

				Utility.syncDownload(mClaimImage.getImageLocation().toString(),
						new AsyncTask<String, Void, Bitmap>() {

							@Override
							protected Bitmap doInBackground(String... params) {

								String newcachepath = params[0];
								ImageDBHelper.insertPaths(mClaimImage
										.getImageLocation().toString(),
										newcachepath);

								return getBitmap(mClaimImage.getImageLocation()
										.toString());
							}

							@Override
							protected void onPostExecute(Bitmap bitmap) {
								hanldeBitmap(bitmap);
							}
						});
			}

			return null;
		}

		@Override
		protected void onPostExecute(Bitmap bitmap) {
			hanldeBitmap(bitmap);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			mProgressBar.setProgress(values[0]);
		}
	}
}
